import {
  nav2
} from "~/tools/nav2"
import {
  ds
} from "../../../tools/data"
import {
  pages
} from '../../../tools/pages'
import {
  roles
} from '../../../tools/roles'
import {
  ui
} from '../../../tools/ui'

const cloudPrefix = getApp().globalData.cloudPrefix

Page({
  data: {
    action: 'manage',
    errMsg: "",
    roles: roles.names,
    cloudPrefix,
    list: [],
    total: 0,
    page: 1,
    pageSize: 5,
    totalPage: 1
  },
  onLoad(option) {
    const {
      action, // select
      role
    } = option
    const title = (this.data.action == 'select' ? '选择用户' : '用户列表')
    this.setData({
      action,
      role,
      title
    })

    wx.setNavigationBarTitle({
      title
    })
    this.init();
  },
  async init() {
    this.loadUsers(this.data.role)
  },
  setPageSize(count) {
    const {
      pageSize
    } = this.data
    const total = count || 0
    this.setData({
      total,
      totalPage: Math.ceil(total / pageSize)
    })
  },
  async loadUsers(role) {
    ui.loading()
    const where = this.buildCondiByRole(role)
    const count = await ds.coll('users').where(where).count()
    this.setPageSize(count.total)
    const {
      page,
      pageSize,
    } = this.data

    ds.coll('users')
      .where(where)
      .orderBy("vip", "desc")
      .orderBy("role", "desc")
      .orderBy("createTime", "asc")
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
      .then((res) => {
        this.setData({
          list: res.data
        })
        ui.loading(false)
      });
  },
  buildCondiByRole(role) {
    const _ = ds.cmd
    const where = {}
    if (role && role != 'all') {
      if (role == 'custom') where.role = _.exists(false).or(_.eq(role))
      else if (role == 'delivery') where.role = _.in(['delivery', 'master'])
      else where.role = _.eq(role)
    }

    return where
  },
  shareClick(e) {

  },
  staffClick(e) {
    if (this.data.action == 'select') {
      // console.log(e)
      const user = e.currentTarget.dataset.user
      pages.back(prePage => {
        prePage.userSelected(user)
      })
      return
    }
    wx.navigateTo({
      url: './edit/index?action=edit&id=' + e.currentTarget.dataset.id,
    })
  },
  avatarLongPress(e) {
    const id = ui.eventData(e, 'id')
    wx.setClipboardData({
      data: id,
    })
  },
  roleTap(e) {
    const id = ui.eventData(e, 'id')
    wx.navigateTo({
      url: `/pages/usercenter/staff/role/index?id=${id}`
    })
  },
  onCancleSelect() {
    pages.back(prePage => {
      prePage.userSelected(null)
    })
  },
  onReachBottom() {
    return
    const {
      total,
      page,
      pageSize,
      totalPage
    } = this.data

    if (page >= totalPage) return this.setData({
      noMore: true
    })

    this.setData({
      page: page + 1
    })
    this.loadUsers()
  },
  onPageChange(e) {
    const {
      page,
      pageSize
    } = e.detail
    this.setData({
      page,
      pageSize
    })
    this.loadUsers()
  },
  onShowRoleTap() {
    const roles = this.data.roles
    roles['all'] = '所有'
    // console.log(roles)
    ui.actionSheet(roles, (value, key) => {
      this.loadUsers(key)
    })
  },
  onDeliveryFeeTap(e) {
    const ds = ui.eventDataset(e)
    nav2.deliveryFee(ds.id, ds.nickname)
  },
  onDeductFeeTap(e) {
    const ds = ui.eventDataset(e)
    nav2.deductFee(ds.id, ds.nickname)
  },
  onPladgeTap(e) {
    const ds = ui.eventDataset(e)
    nav2.pladge(ds.id)
  },
  // 分享注册链接
  onShareAppMessage(e) {
    // console.log(e.from) //转发事件来源 button：页面内转发按钮 menu：右上角转发菜单
    // console.log(e.target) //如果from值是button，则target是触发这次转发事件的button，否则为undefined
    let url = '/pages/usercenter/person-info/index'
    return {
      title: '用户注册-万家顺送水',
      path: url,
      imageUrl: cloudPrefix + '/static/img/logo200x160.jpg', // 缩略图，如果不设置取系统默认截图
      success: function (res) {
        ui.toast(true, '分享成功')
      },
      fail: function (res) {

      }
    }
  },

});